import random
import json
import os
from generate_words_util import GenerateWordsUtil

class CreateJsonFiles:

    def __init__(self):
        self.gen_words = GenerateWordsUtil()

        if not os.path.exists('output_jsons'):
            os.makedirs('output_jsons')
        
    def get_class_types(self):
        """返回所有可用的类型"""
        return ["UITabelView", 'UICollectionView', 'UIView', 'UIViewController', 'CATBaseTipView']
    
    def get_view_types(self):
        """返回所有可用的视图类型"""
        return ["UIView", "UILabel", "UIButton", "UIImageView", "UITextFeield", "UISwitch", 'UISlider']
            
    def create_json(self, type_index=0, subviews=None, fila_name=None):
        """
        生成完整的JSON结构
        classType = ["UITabelView", 'UICollectionView', 'UIView', 'UIViewController', 'CATBaseTipView']
        """
        class_type = self.get_class_types()

        view_types = self.get_view_types()

        if not fila_name:
            fila_name = "Test"

        if subviews is None:
            subviews = random.sample(view_types, random.randint(1, 4))
        
        subview_datas = []
        for view_type in subviews:
            subview = self.subview_json_data(view_type)
            subview_datas.append(subview)

        class_type = class_type[type_index]
        data = {
            "classType": class_type,
            "moudle": "Login",
            "prefix": "CAT",
            "classDesc": "登录页"
        }

        if class_type == 'CATBaseTipView':
            data['is_class_return'] = True
        
        if subview_datas:
            data['subviews'] = subview_datas

        filepath = os.path.join('output_jsons', f'{fila_name}.json')
        with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(data, f, indent=2)
        
        return filepath
    
    def create_json_with_config(self, type_index=0, subviews=None, file_name=None, module="Login", prefix="CAT", class_desc="登录页"):
        """
        使用自定义配置生成JSON文件
        """
        class_types = self.get_class_types()
        view_types = self.get_view_types()

        if not file_name:
            file_name = "Test"

        if subviews is None or len(subviews) == 0:
            subviews = random.sample(view_types, random.randint(1, 4))
        
        subview_datas = []
        for view_type in subviews:
            if isinstance(view_type, dict):
                # 如果是完整的子视图配置
                subview_datas.append(view_type)
            else:
                # 如果只是视图类型字符串
                subview = self.subview_json_data(view_type)
                subview_datas.append(subview)

        class_type = class_types[type_index]
        data = {
            "classType": class_type,
            "moudle": module,
            "prefix": prefix,
            "classDesc": class_desc
        }

        if class_type == 'CATBaseTipView':
            data['is_class_return'] = True
        
        if subview_datas:
            data['subviews'] = subview_datas

        filepath = os.path.join('output_jsons', f'{file_name}.json')
        with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(data, f, indent=2)
        
        return filepath
    
    def subview_json_data(self, view_type):
        """
        生成子视图的JSON结构
        """
        constraints = {}
        properties = {
            "backgroundColor": "rgba(0, 0, 0, 1)",
            "alpha": random.choice([0.8, 0.9, 1.0]),
            "isHidden": random.choice([True, False, False]),  # 大多数情况下不隐藏
            "clipsToBounds": random.choice([True, False]),
            "tag": random.randint(100, 999),
            "isUserInteractionEnabled": random.choice([True, False]),
            "contentMode": random.choice(["scaleAspectFit", "scaleAspectFill", "center"]),
            "cornerRadius": random.randint(0, 10),
            "borderWidth": random.choice([0, 1, 2]),
            "borderColor": "rgba(0, 0, 0, 1)"
        }

        if view_type == "UILabel":
            properties["text"] = f"标签"
            properties["textColor"] = "rgba(0, 0, 0, 1)"
            properties["fontSize"] = random.randint(12, 20)
            properties["fontWeight"] = random.choice(["regular", "medium", "bold"])
            properties["numberOfLines"] = random.choice([0, 1, 2])
            properties["textAlignment"] = random.choice(["left", "center", "right"])
            
        elif view_type == "UIButton":
            properties["cornerRadius"] = random.randint(3, 10)
            properties["clipsToBounds"] = True
            properties["title"] = "按钮"
            properties["titleColor"] = "rgba(0, 0, 0, 1)"
            properties["fontSize"] = random.randint(12, 18)
            properties["fontWeight"] = random.choice(["regular", "medium", "bold"])
            properties["action"] = f"button{random.randint(1, 100)}Tapped"
            properties["contentHorizontalAlignment"] = random.choice(["center", "left", "right"])
            # 添加图片相关属性
            properties["image"] = ""  # 正常状态图片
            properties["highlightedImage"] = ""  # 高亮状态图片
            properties["selectedImage"] = ""  # 选中状态图片
            properties["imageEdgeInsets"] = "UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)"  # 图片内边距
            properties["imageContentMode"] = random.choice(["scaleAspectFit", "scaleAspectFill", "center"])
        
        elif view_type == "UITextFeield":
            properties["text"] = f"输入框"
            properties["textColor"] = "rgba(0, 0, 0, 1)"
            properties["fontSize"] = random.randint(12, 20)
            properties["placeholder"] = "请输入"
            properties["textAlignment"] = random.choice(["left", "center", "right"])
            properties["keyboardType"] = random.choice(["default", "numberPad", "emailAddress"])
            properties["returnKeyType"] = random.choice(["done", "next", "search"])
            properties["delegate"] = True
        
        elif view_type == "UISwitch":
            properties["isOn"] = random.choice([True, False])
            properties["onTintColor"] = "rgba(0, 0, 0, 1)"
            properties["thumbTintColor"] = "rgba(0, 0, 0, 1)"
            properties["action"] = f"switch{random.randint(1, 100)}Changed"
        
        elif view_type == "UISlider":
            properties["minimumValue"] = 0
            properties["maximumValue"] = 100
            properties["value"] = random.randint(0, 100)
            properties["minimumTrackTintColor"] = "rgba(0, 0, 0, 1)"
            properties["maximumTrackTintColor"] = "rgba(0, 0, 0, 1)"
            properties["thumbTintColor"] = "rgba(0, 0, 0, 1)"
            properties["action"] = f"slider{random.randint(1, 100)}Changed"
        
        elif view_type == "UIImageView":
            properties["image"] = ""  # 图片路径
            
        # 保持constraints为字典格式
        constraints['top'] = 10
        constraints['leading'] = 10
        constraints['trailing'] = 10
        constraints['bottom'] = 10
        constraints['centerX'] = 10
        constraints['centerY'] = 10
        constraints['width'] = 100
        constraints['height'] = 50


        subview = {
            "view_type": view_type,
            "view_des": f"{view_type}",
            "properties": properties,
            "constraints": constraints
        }
        return subview


if __name__ == "__main__":
    creator = CreateJsonFiles()
    # def create_json(self, type_index=0, subviews=None, fila_name=None):
    # creator.create_json(4, subviews = ['UILabel', 'UIButton', 'UIButton', 'UILabel', 'UIButton', 'UIButton'], fila_name="FilterPlus")
    creator.create_json(2, subviews = ['UILabel', 'UIImageView', 'UILabel', 'UIImageView'], fila_name="FilterText")
    creator.create_json(2, subviews = ['UILabel', 'UILabel'], fila_name="FilterSlider")
    # 生成一个随机的JSON文件
    # random_file = creator.create_random_json(5)
    # print(f"已生成随机JSON文件: {random_file}")
        